package org.com.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.com.mapper.FarmsImagesMapper;
import org.com.pojo.Farms;
import org.com.pojo.FarmsImages;
import org.com.service.FarmsService;
import org.com.mapper.FarmsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.com.vo.FarmApplyVO;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.util.Date;
import org.com.service.UserBalanceService;
import org.com.service.TransactionsService;
import org.com.pojo.UserBalance;
import org.com.pojo.Transactions;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;

import java.util.List;

/**
 * @author 86134
 * @description 针对表【farms】的数据库操作Service实现
 * @createDate 2025-02-27 16:34:36
 */
@Slf4j
@Service
public class FarmsServiceImpl extends ServiceImpl<FarmsMapper, Farms>
        implements FarmsService {
    @Autowired
    private FarmsMapper farmsMapper;
    @Autowired
    private FarmsImagesMapper farmsImagesMapper;
    
    @Autowired
    private UserBalanceService userBalanceService;
    
    @Autowired
    private TransactionsService transactionsService;
    
    @Override
    public boolean addFarms(Farms farms, String url) {
        // 检查农场名称是否已存在
        QueryWrapper<Farms> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", farms.getUserId())
                   .eq("farm_name", farms.getFarmName());
        
        if (farmsMapper.selectOne(queryWrapper) != null) {
            log.warn("农场名称已存在: {}", farms.getFarmName());
            return false;
        }

        // 使用MyBatis-Plus的insert方法插入农场信息
        log.info("开始插入农场信息: {}", farms.getFarmName());
        boolean result = save(farms);
        log.info("农场信息插入结果: {}, 生成的ID: {}", result, farms.getFarmId());

        if (!result) {
            log.error("农场信息插入失败");
            return false;
        }

        // 获取插入后的农场ID
        Integer farmId = farms.getFarmId();
        if (farmId == null) {
            log.error("未能获取到生成的农场ID");
            return false;
        }

        // 创建并插入农场图片
        FarmsImages farmImage = new FarmsImages();
        farmImage.setFarmId(farmId);
        farmImage.setImageUrl(url);
        farmImage.setIsPrimary(1);

        boolean imageResult = farmsImagesMapper.insertFarmsImages(farmImage);
        log.info("农场图片插入结果: {}", imageResult);
        return imageResult;
    }

    @Override
    public List<Farms> getUserFarms(Integer userId) {
        log.info("开始查询用户农场列表, userId: {}", userId);
        if (userId == null) {
            log.error("用户ID为空");
            throw new IllegalArgumentException("用户ID不能为空");
        }
        try {
            List<Farms> farms = farmsMapper.selectUserFarmsWithDetails(userId);
            log.info("查询到农场数量: {}", farms != null ? farms.size() : 0);
            return farms;
        } catch (Exception e) {
            log.error("查询用户农场列表失败", e);
            throw e;
        }
    }

    @Override
    public List<FarmApplyVO> getApplyFarms() {
        log.info("开始获取农场申请列表");
        List<FarmApplyVO> farms = farmsMapper.getApplyFarms();
        log.info("获取到农场数量: {}", farms.size());
        
        for (FarmApplyVO farm : farms) {
            log.info("农场详细信息:");
            log.info("- ID: {}", farm.getFarmId());
            log.info("- 名称: {}", farm.getFarmName());
            log.info("- 地址: {}", farm.getFarmAddress());
            log.info("- 状态: {}", farm.getStatusText());
            log.info("- 申请补贴金额: {}", farm.getAppliedSubsidyAmount());
            log.info("- 申请人: {} ({})", farm.getCallName(), farm.getUserName());
            log.info("- 图片信息: ID={}, URL={}", 
                farm.getImageId(), 
                farm.getImageUrl() != null ? farm.getImageUrl() : "无图片"
            );
            log.info("----------------------------------------");
        }
        return farms;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean approveFarmApplication(Integer farmId, Integer adminUserId, Integer farmUserId, BigDecimal amount) {
        log.info("我被调用了",
                farmId, adminUserId, farmUserId, amount);
        
        try {
            // 1. 更新管理员余额（减少）
            UpdateWrapper<UserBalance> adminBalanceUpdate = new UpdateWrapper<>();
            adminBalanceUpdate.eq("user_id", adminUserId)
                            .setSql("balance = balance - " + amount);
            boolean adminBalanceResult = userBalanceService.update(adminBalanceUpdate);
            if (!adminBalanceResult) {
                log.error("更新管理员余额失败");
                throw new RuntimeException("更新管理员余额失败");
            }

            // 2. 更新农场主余额（增加）
            UpdateWrapper<UserBalance> farmerBalanceUpdate = new UpdateWrapper<>();
            farmerBalanceUpdate.eq("user_id", farmUserId)
                             .setSql("balance = balance + " + amount);
            boolean farmerBalanceResult = userBalanceService.update(farmerBalanceUpdate);
            if (!farmerBalanceResult) {
                log.error("更新农场主余额失败");
                throw new RuntimeException("更新农场主余额失败");
            }

            // 3. 记录管理员支出交易
            Transactions adminTransaction = new Transactions();
            adminTransaction.setUserId(adminUserId);
            adminTransaction.setDelta(amount.negate());
            adminTransaction.setStatus(3); // 支出
            adminTransaction.setCreatedAt(new Date());
            
            // 获取管理员的 balance_id
            UserBalance adminBalance = userBalanceService.getOne(
                new QueryWrapper<UserBalance>().eq("user_id", adminUserId)
            );
            if (adminBalance != null) {
                adminTransaction.setBalanceId(adminBalance.getBalanceId());
            }
            
            boolean adminTransactionResult = transactionsService.save(adminTransaction);
            if (!adminTransactionResult) {
                log.error("记录管理员交易失败");
                throw new RuntimeException("记录管理员交易失败");
            }

            // 4. 记录农场主收入交易
            Transactions farmerTransaction = new Transactions();
            farmerTransaction.setUserId(farmUserId);
            farmerTransaction.setDelta(amount);
            farmerTransaction.setStatus(0); // 收入
            farmerTransaction.setCreatedAt(new Date());
            boolean farmerTransactionResult = transactionsService.save(farmerTransaction);
            if (!farmerTransactionResult) {
                log.error("记录农场主交易失败");
                throw new RuntimeException("记录农场主交易失败");
            }

            // 5. 更新农场状态为已通过
            UpdateWrapper<Farms> farmUpdate = new UpdateWrapper<>();
            farmUpdate.eq("farm_id", farmId)
                     .set("status_id", 2); // 设置为营业中状态
            boolean farmUpdateResult = this.update(farmUpdate);
            if (!farmUpdateResult) {
                log.error("更新农场状态失败");
                throw new RuntimeException("更新农场状态失败");
            }

            log.info("农场审批处理完成");
            return true;
        } catch (Exception e) {
            log.error("农场审批处理失败", e);
            throw new RuntimeException("农场审批处理失败: " + e.getMessage());
        }
    }

    @Override
    public List<String> getFarmImages(Integer farmId) {
        log.info("获取农场图片, farmId: {}", farmId);
        return farmsImagesMapper.selectImageUrlsByFarmId(farmId);
    }

    @Override
    @Transactional
    public boolean updateFarmInfo(Farms farm, List<String> newImageUrls, List<String> deletedImageUrls) {
        try {
            // 1. 更新农场基本信息
            boolean updateResult = this.updateById(farm);
            if (!updateResult) {
                return false;
            }

            // 2. 处理新增的图片
            if (newImageUrls != null && !newImageUrls.isEmpty()) {
                for (String imageUrl : newImageUrls) {
                    FarmsImages farmImage = new FarmsImages();
                    farmImage.setFarmId(farm.getFarmId());
                    farmImage.setImageUrl(imageUrl);
                    farmImage.setIsPrimary(0); // 新增的图片默认不是主图
                    farmsImagesMapper.insertFarmsImages(farmImage);
                }
            }

            // 3. 处理需要删除的图片
            if (deletedImageUrls != null && !deletedImageUrls.isEmpty()) {
                // 构建删除条件
                QueryWrapper<FarmsImages> deleteWrapper = new QueryWrapper<>();
                deleteWrapper.eq("farm_id", farm.getFarmId())
                           .in("image_url", deletedImageUrls);
                farmsImagesMapper.delete(deleteWrapper);
            }

            return true;
        } catch (Exception e) {
            log.error("更新农场信息失败", e);
            throw new RuntimeException("更新农场信息失败：" + e.getMessage());
        }
    }
}




